<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="新增应用" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" name="SaveApp" setup>
  import { ref, computed, unref } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { newAppFormSchema } from "./data"
  import * as appApi from "/@/api/iam/app"
  import { useMessage } from "/@/hooks/web/useMessage"

  const { createMessage, createConfirm } = useMessage()

  const emit = defineEmits(["success", "register"])
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: newAppFormSchema,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  })
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields()
    setModalProps({ confirmLoading: false })
    await setFieldsValue({ ...data })
  })
  async function handleSubmit() {
    try {
      const values = await validate()
      setModalProps({ confirmLoading: true })
      const appId = await appApi.saveApp(values)
      closeModal()
      createMessage.success("创建成功")
      emit("success", appId)
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
